﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.ServiceModel.Web;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Security;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
{
    public class AppController : ApiController
    {

        public bool Post(LoginModel model)
        {
            if (Membership.ValidateUser(model.UserName, model.Password))
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false);
                return true;
            }
            return false;
        }

       
        private static readonly IDictionary<int, string> _images = new Dictionary<int, string>();

        private static readonly IDictionary<string, string> _extensions =
            new Dictionary<string, string>()
                {
                    {".gif", "image/gif"},
                    {".jpg", "image/jpeg"},
                    {".jpeg", "image/jpeg"},
                    {".png", "image/png"},
                    {".svg", "image/svg+xml"}
                };

        public Task<HttpResponseMessage> PostImage()
        {

            HttpRequestMessage request = this.Request;
            if (!request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
            var provider = new MultipartFormDataStreamProvider(root);

            var task = request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<HttpResponseMessage>(o =>
                {
                    try
                    {


                        var parts = o.Result;

                        //                    HttpContent idPart = parts.FirstDispositionNameOrDefault("id");
                        HttpContent idPart = parts.ElementAt(2);

                        if (idPart == null)
                        {
                            throw new HttpResponseException(HttpStatusCode.BadRequest);
                        }
                        if (provider.BodyPartFileNames.Count != 1)
                        {
                            throw new HttpResponseException(HttpStatusCode.BadRequest);
                        }

                        int id = int.Parse(idPart.ReadAsStringAsync().Result);

                        AddImage(id, provider.BodyPartFileNames.First().Value);

                        return new HttpResponseMessage()
                        {
                            Content = new StringContent("File uploaded.")
                        };
                    }
                    catch (Exception exception)
                    {

                        throw;
                    }
                }
                );
            return task;
        }

        private void AddImage(int id, string path)
        {
            try
            {
                string ext = Path.GetExtension(path).ToLowerInvariant();
                if (!_extensions.Keys.Contains(ext))
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                string oldImage;
                if (_images.TryGetValue(id, out oldImage))
                {
                    File.Delete(oldImage);
                }
                _images[id] = path;
            }
            catch (Exception exception)
            {

                throw;
            }

        }

    }
}